<template>
  <el-drawer
      v-model="drawerOpen"
      direction="rtl"
      size="calc(100vw - 180px)"
      :with-header="false"
      :close-on-click-modal="false"
      :before-close="handleClose">
    <div style="width: 100%">
      <div style="background: #eee;padding: 10px;margin: 10px 0;" class="flex align-center justify-content-between">
        <div class="flex align-center">
          <el-button @click="handleAddChapter" icon="plus" type="success">添加章</el-button>
          <span class="ml20">当前课程id是：{{ courseId }}</span>
        </div>
        <el-button type="danger" icon="close" @click="handleClose">关闭</el-button>
      </div>
    </div>
    <el-row>
        <el-col :span="12">
          <el-tree
              style="max-width: 100%"
              :data="chapterList"
              :props="{ id: 'id',label:'title' }"
              node-key="id"
              ref="treeRef"
              default-expand-all
              @node-click="handleNodeClick"
              :expand-on-click-node="false"
          >
            <template #default="{ node, data}">
              <div class="custom-tree-node flex justify-content-between w100 align-center">
                <span class="flex1">第{{ data.index + 1 }}{{ data.label }}：{{ node.label }}</span>
                <span>
                   <el-switch
                       v-if="!data.children"
                       size="small"
                       class="mr15"
                       v-model="data.freeFlag"
                       @change="handleFreeFlag(data, 'freeFlag')"
                       :active-value="1"
                       inline-prompt
                       active-text="收费中"
                       inactive-text="免费中"
                       :inactive-value="0"
                   ></el-switch>
                    <el-button icon="plus" size="small" v-if="data.children" @click="handleAppend(node,data)" type="success" >添加节</el-button>
                    <el-button icon="edit" size="small" v-if="data.children"  @click="handleEditChapter(node,data,'chapter')" type="primary" >编辑</el-button>
                    <el-button icon="edit" size="small" v-else  @click="handleEditLesson(node,data,'lesson')" type="primary" >编辑</el-button>
                    <el-button icon="close" size="small" v-if="data.children" @click="handleRemoveChapter(node,data)" type="danger" >删除</el-button>
                    <el-button icon="close" size="small" v-else @click="handleRemoveLesson(node,data)" type="danger" >删除</el-button>
                    <el-button icon="CopyDocument" size="small" v-if="data.children" @click="handleCopyChapter(node,data)" type="warning" >复制</el-button>
                    <el-button icon="CopyDocument" size="small" v-else @click="handleCopyLesson(node,data)" type="warning" >复制</el-button>
                    <el-switch
                        size="small"
                        class="ml15"
                        v-model="data.status"
                        @change="handleStatus(data, 'status',(data.children?'chapter':'lesson'))"
                        :active-value="1"
                        inline-prompt
                        active-text="已发布"
                        inactive-text="未发布"
                        :inactive-value="0"
                    ></el-switch>
                    <el-tooltip :content="data.children?'章排序':'节排序'" placement ="top">
                      <el-input size="small" @blur="handleStatus(data,'sorted',(data.children?'chapter':'lesson'))" style="width: 60px;margin-left: 10px;text-align: center" placeholder="排序" v-model="data.sorted"></el-input>
                    </el-tooltip>
                  </span>
              </div>
            </template>
          </el-tree>
        </el-col>
        <el-col :span="9" v-if="mode=='chapter'">
          <el-form
              ref="formRef"
              label-width="100px"
              :model="form"
              style="padding: 30px"
              :rules="rules"
          >
            <el-form-item label="隶属课程："  required prop="courseTitle">
              <el-input v-model="form.courseTitle" autocomplete="off" disabled maxlength="200" placeholder="隶属课程" />
            </el-form-item>
            <el-form-item label="章标题：" required prop="title">
              <el-input v-model="form.title" autocomplete="off" maxlength="60" placeholder="章标题" />
            </el-form-item>
            <el-form-item label="章排序：" required prop="sorted">
              <el-input-number v-model="form.sorted" autocomplete="off" maxlength="10" placeholder="章排序" />
            </el-form-item>
            <el-form-item label="是否启用：" required prop="status">
              <el-radio-group v-model="form.status">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="总时长：" prop="totalTime">
              <el-input v-model="form.totalTime" maxlength="100" placeholder="总时长" />
            </el-form-item>
            <el-form-item  prop="status">
              <el-button type="primary" :loading="suLoading" @click="handleSubmit" icon="plus">{{
                  form.id ? '更新章' : '保存章'
                }}</el-button>
              <el-button @click="handleReset" icon="remove">取消</el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="9" v-if="mode=='lesson'">
        <el-form
            ref="formRef"
            label-width="180px"
            :model="form"
            style="padding: 30px"
            :rules="rules"
        >
          <el-form-item label="隶属课程："  required prop="courseTitle">
            <el-input v-model="form.courseTitle" autocomplete="off" disabled maxlength="200" placeholder="隶属课程" />
          </el-form-item>
          <el-form-item label="隶属章：" required prop="chapterTitle">
            <el-input v-model="form.chapterTitle" autocomplete="off" disabled maxlength="200" placeholder="隶属章" />
          </el-form-item>
          <el-form-item label="保利威视播放码：" required prop="videoid">
            <div class="flex w100">
              <el-input v-model="form.videoid" maxlength="100" placeholder="保利威视播放码"/>
              <el-button @click="handleParseVideo" type="success">解析</el-button>
            </div>
          </el-form-item>
          <el-form-item label="节标题：" required  prop="title">
            <el-input v-model="form.title" autocomplete="off" maxlength="60" placeholder="节标题" />
          </el-form-item>
          <el-form-item label="节排序：" required prop="sorted">
            <el-input-number v-model="form.sorted" autocomplete="off" maxlength="10" placeholder="节排序" />
          </el-form-item>
          <el-form-item label="节时长（s）：" prop="duration">
            <el-input v-model="form.duration" maxlength="100" placeholder="节时长" />
          </el-form-item>
          <el-form-item label="视频大小：" prop="videosize">
            <el-input v-model="form.videosize" maxlength="100" placeholder="视频大小" />
          </el-form-item>
          <el-form-item label="视频播放次数：" prop="playcount">
            <el-input v-model="form.playcount" maxlength="100" placeholder="视频播放次数" />
          </el-form-item>
          <el-form-item label="保利威视源视频地址：" prop="videoSourceUrl">
            <el-input v-model="form.videoSourceUrl" maxlength="400" placeholder="保利威视源视频地址" />
            <div style="background: #000;padding:10px;margin: 10px 0;">
              <video :src="form.videoSourceUrl" width="400" height="200" controls></video>
            </div>
          </el-form-item>
          <el-form-item label="是否免费：" required prop="freeFlag">
            <el-radio-group v-model="form.freeFlag">
              <el-radio :label="1">收费</el-radio>
              <el-radio :label="0">免费</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否启用：" required prop="status">
            <el-radio-group v-model="form.status">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item  prop="status">
            <el-button type="primary" :loading="suLoading" @click="handleSubmit" icon="plus">{{
                form.id ? '更新'+(mode=='chapter'?'章':'节') : '保存'+(mode=='chapter'?'章':'节')
              }}</el-button>
            <el-button @click="handleReset" icon="remove">取消</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      </el-row>
  </el-drawer>
</template>
<script setup>
import KVA from "@/utils/kva";
import {copyData, findPages,saveUpdate,removeById,updateStatus} from '@/api/course/chapter.js'
import {copyData as copyDataLesson, parseVideo,saveUpdate as saveLesson,removeById as removeLesson,updateStatus as updateLessonStatus} from '@/api/course/lesson.js'
import debounce from '@/utils/debounce'

const drawerOpen = ref(false)
const chapterList = ref([])
const mode = ref("chapter")
const suLoading = ref(false)
const currentNode = ref({})
const courseId = ref(0)
const courseTitle =ref("")
const currentChapter = ref({})

// 这个数据模型
let form = ref({
  title:"",
  sorted:1,
  totalTime:"",
  status:1,
  chapterId:"",
  playcount:0,
  videosize:'0',
  videoid:"",
  duration:"",
  freeFlag:1,
  videoSourceUrl:"",
  chapterTitle:"",
})
// 表单ref, 用于提交最终得验证处理
const formRef = ref({})
const treeRef = ref({})
// 表单验证
const rules = reactive({
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }]
})

// 保存和修改
const handleSubmit = () => {
  suLoading.value = true
  debounce(() => {
    formRef.value.validate(async (valid, fields) => {
      if (valid) {
        try {
          if(mode.value == 'chapter') {
            await saveUpdate(form.value)
          }else{
            await saveLesson(form.value)
            currentChapter.value.children.push({})
          }
          suLoading.value = false
          // 提示保存成功
          KVA.notifySuccess(form.value.id ? '更新成功' : '保存成功')
          // 关闭弹窗
          handleOpen(courseId.value,courseTitle.value)
          handleReset()
          form.value.courseTitle = courseTitle.value
          form.value.courseId = courseId.value
          form.value.chapterId = currentChapter.value.id
          form.value.chapterTitle = currentChapter.value.title
          form.value.sorted = form.value.sorted*1 + 1
          // 刷新方法
        } catch (ex) {
          suLoading.value = false
        }
      } else {
        suLoading.value = false

      }
    })
  }, 600)
}

const getNodeIndex = (node, index = 0) => {
  node.index = index;
  if (node.children && node.children.length == 0) {
    node.label = "章"
    return
  }
  if (node.children && node.children.length > 0) {
    node.label = "章"
    node.children.forEach((child, i) => {
      getNodeIndex(child, i);
    });
  } else {
    node.label = "节"
  }
}

const handleOpen = async (id,title) => {
  courseId.value = id
  courseTitle.value = title
  form.value.courseId = id
  form.value.courseTitle = title
  drawerOpen.value = true
  const resp = await findPages(id)
  form.value.sorted = mode.value=='chapter'?(resp.data.length + 1):(currentChapter.value?.children?.length+1)
  chapterList.value = resp.data.map((c, index) => {
    getNodeIndex(c, index)
    return c
  })
}

// 添加章
const handleAddChapter = ()=>{
  mode.value = "chapter"
  handleReset();
  form.value.id = ''
  form.value.courseId = courseId.value
  form.value.courseTitle = courseTitle.value
  form.value.sorted = chapterList.value.length + 1
}


// 添加节
const handleAppend = (node,data) => {
  mode.value = "lesson"
  currentNode.value = node
  form.value.id = '';
  currentChapter.value = data
  form.value.chapterId = data.id;
  form.value.chapterTitle = data.title;
  form.value.sorted = data.children.length + 1
  form.value.courseId = courseId.value
  form.value.courseTitle = courseTitle.value

  form.value.title = "";
  form.value.status = 1;
  form.value.playcount = 0;
  form.value.videoid = '';
  form.value.duration = 0;
  form.value.videosize = 0;
  form.value.freeFlag = 1;
  form.value.videoSourceUrl = '';
}

// 编辑章
const handleEditChapter = (node,data) =>{
  mode.value = "chapter"
  currentNode.value = node
  form.value.id = data.id;
  form.value.title = data.title;
  form.value.sorted = data.sorted
  form.value.totalTime = data.totalTime
  form.value.status = data.status;
  form.value.courseId = courseId.value
  form.value.courseTitle = courseTitle.value
}

// 编辑节
const handleEditLesson = (node,data) =>{
  mode.value = "lesson"
  currentNode.value = node
  form.value.id = data.id;
  form.value.title = data.title;
  form.value.sorted = data.sorted
  form.value.status = data.status;
  form.value.playcount = data.playcount;
  form.value.videoid = data.videoid;
  form.value.duration = data.duration;
  form.value.videosize = data.videosize;
  form.value.freeFlag = data.freeFlag;
  form.value.videoSourceUrl = data.videoSourceUrl;
  form.value.chapterId = data.chapterId;
  form.value.chapterTitle = data.chapterTitle;
  form.value.courseId = courseId.value
  form.value.courseTitle = courseTitle.value
}

// 删除章
const handleRemoveChapter = (node,data) =>{
  KVA.confirm('警告', '<strong>您确定要执行删除【章】操作吗？</strong>', { icon: 'success' }).then(async () => {
    KVA.confirm('警告', '<strong>一旦执行相关的【节】全部删除！</strong>', { icon: 'success' }).then(async () => {
      await removeById(data.id)
      KVA.notifySuccess('删除成功!')
      treeRef.value.remove(node)
    })
  })
}

// 删除节
const handleRemoveLesson = (node,data) =>{
  KVA.confirm('警告', '<strong>您确定要执行删除【节】操作！</strong>', { icon: 'success' }).then(async () => {
    await removeLesson(data.id)
    KVA.notifySuccess('删除成功!')
    treeRef.value.remove(node)
  })
}

// 设置收费免费
const handleFreeFlag = (data,field) =>{
  if(!data.id)return
  updateLessonStatus(data.id,field,data[field])
  KVA.notifySuccess('设置成功!')
  handleOpen(courseId.value,courseTitle.value)
}

// 设置收费免费
const handleStatus = async(data,field,mode) =>{
  if(!data.id)return
  if(mode == "chapter") {
    await updateStatus(data.id, field, data[field])
  }else{
    await updateLessonStatus(data.id, field, data[field])
  }
  KVA.notifySuccess('操作成功!')
  handleOpen(courseId.value,courseTitle.value)
}

// 解析视频
const handleParseVideo = async ()=>{
  const resp = await parseVideo(form.value.videoid)
  form.value.duration = resp.data.duration;
  form.value.title = resp.data.title;
  form.value.videoSourceUrl = resp.data.defaultVideo;
  form.value.videosize = resp.data.sourceFileSize;
}

const handleNodeClick = (data, node) => {
  console.log(node.index);
}

// 重置
const handleReset = ()=>{
  form.value = {
    id:"",
    title:"",
    totalTime:"",
    status:1,
    playcount:0,
    videosize:'0',
    videoid:"",
    duration:"",
    freeFlag:1,
    videoSourceUrl:"",
  }
}

const handleCopyChapter = async (node,row)=>{
  await copyData(row.id);
  KVA.success("复制成功!!")
  handleOpen(courseId.value,courseTitle.value)
}

const handleCopyLesson = async (node,row)=>{
  await copyDataLesson(row.id);
  KVA.success("复制成功!!")
  handleOpen(courseId.value,courseTitle.value)
}


const handleClose = () => {
  drawerOpen.value = false
  handleReset()
}

defineExpose({
  handleOpen,
  handleClose
})
</script>
<style>
.el-tree-node__content{padding:1px 0!important;}
.el-tree-node__children{margin-left: 15px;}
</style>